package web;

import beans.LoginStatus;
import beans.User;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import service.UserService;
import utils.ResultUtils;

import java.io.IOException;

@WebServlet("/user/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取页面传递的参数值
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //将页面的参数进行封装
        User user = new User(username,password);

        //调用UserService处理业务逻辑 登录逻辑处理
        UserService userService = new UserService();
        User existUser = userService.login(user);

        //根据existUser的结果 去做判断
        String responseData;//存储响应是的数据
        if (existUser!=null){
            //登录成功   将用户信息（会话状态）存储到session中
            request.getSession().setAttribute("existUser",existUser);

            //登录成功并且勾选了复选框的，此时要写一个cookie
            String autoLogin = request.getParameter("autoLogin");
            if (autoLogin!=null&&autoLogin.equals("on")){
                Cookie cookie = new Cookie("autoLogin",user.getUsername()+"#"+user.getPassword());
                cookie.setMaxAge(7*24*60*60);
                cookie.setPath(request.getContextPath());
                response.addCookie(cookie);
            }

            responseData=ResultUtils.result(LoginStatus.LOGIN_SUCCESS,new User(username,password));
        }else {
            //登录失败
            responseData = ResultUtils.result(LoginStatus.LOGIN_FAIL, new User(username, password));
        }

        response.getWriter().write(responseData);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
